<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/14
 * Time: 11:44
 */

namespace app\api\model;


class Category extends BaseModel
{
    protected $autoWriteTimestamp = true;
    protected $hidden =['topic_img_id','delete_time','description','update_time','t_id','create_time'];

    /**
     * 与图片表一对一关联
     * @return \think\model\relation\BelongsTo
     */
    public function img(){
        return $this->belongsTo('Image','topic_img_id','id');
    }

    /**
     * 与商品规格表一对多关联
     * @return \think\model\relation\BelongsToMany
     */
    public function property(){
        return $this->hasMany('ProductProperty','category_id','id');
    }

    /**
     * 获取所有分类
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getAllCategory($t_id){
        $result = self::with('img')->where('t_id','=',$t_id)->select();
        return $result;
    }

    /**
     * 获取分类
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getCategory($id){
        $result = self::with('img')->where('id','=',$id)->find();
        return $result;
    }

    /**
     * 创建分类
     * @param $info
     * @param $uid
     * @return $this
     */
    public static function createCategory($info,$uid){
        $data['name'] = $info['name'];
        $data['topic_img_id'] = $info['topic_img_id'];
        $data['t_id'] =$uid;
        $result = self::create($data);
        return $result;
    }

    /**
     * 更新分类
     * @param $info
     * @param $uid
     * @return false|int
     */
    public static function updateCategory($info,$uid){
        $data['name'] = $info['name'];
        $data['topic_img_id'] = $info['topic_img_id'];
        $data['t_id'] = $uid;
        $result = (new Category)->save($data,['id'=>$info['id']]);
        return $result;
    }
    /**
     * 删除分类
     * @param $c_id
     * @return int
     */
    public static function deleteCategory($c_id){
        $result = self::destroy($c_id);
        return $result;
    }
    /**
     * 获取分类的规格参数
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getProperty($t_id){
        $result = self::with('img')->where('t_id','=',$t_id)->with('property')->select();
        foreach ($result as $value){
            $value->property->visible(['id','name']);
        }
        return $result;
    }


}